<template>
  <div>
    <el-button type="primary" @click="dialogVisible = true">新增题目</el-button>
    <el-table :data="questions" style="width: 100%; margin-top: 20px">
      <el-table-column label="题目id" prop="id"></el-table-column>
      <el-table-column label="题目标题" prop="title"></el-table-column>
      <el-table-column label="题目标签" prop="tags"></el-table-column>
      <el-table-column label="提交数量" prop="submitNum"></el-table-column>
      <el-table-column label="通过数量" prop="acceptNum"></el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button @click="editQuestion(row)" type="text" size="small"
            >编辑</el-button
          >
          <el-button
            disabled
            @click="deleteQuestion(row.id)"
            type="text"
            size="small"
            style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑题目对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加题目"
      width="50%"
      :before-close="handleClose"
    >
      <el-form :model="newQuestion">
        <el-form-item label="题目标题" required>
          <el-input v-model="newQuestion.title"></el-input>
        </el-form-item>
        <el-form-item label="题目标签" required>
          <el-input v-model="newQuestion.tags"></el-input>
        </el-form-item>
        <!-- 题目内容编辑器 -->
        <el-form-item label="题目内容" required>
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
            />
            <Editor
              style="height: 200px; overflow-y: hidden"
              v-model="newQuestion.content"
              :defaultConfig="editorConfig"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
        <el-form-item label="输入描述" required>
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="inputDescEditorRef"
              :defaultConfig="toolbarConfig1"
            />
            <Editor
              style="height: 200px; overflow-y: hidden"
              v-model="newQuestion.inputDescription"
              :defaultConfig="editorConfig1"
              @onCreated="handleInputDescCreated"
            />
          </div>
        </el-form-item>

        <el-form-item label="输出描述" required>
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="outputDescEditorRef"
              :defaultConfig="toolbarConfig"
            />
            <Editor
              style="height: 200px; overflow-y: hidden"
              v-model="newQuestion.outputDescription"
              :defaultConfig="editorConfig"
              @onCreated="handleOutputDescCreated"
            />
          </div>
        </el-form-item>

        <el-form-item label="输入样例" required>
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="inputExampleEditorRef"
              :defaultConfig="toolbarConfig"
            />
            <Editor
              style="height: 200px; overflow-y: hidden"
              v-model="newQuestion.inputContent"
              :defaultConfig="editorConfig"
              @onCreated="handleInputExampleCreated"
            />
          </div>
        </el-form-item>

        <el-form-item label="输出样例" required>
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="outputExampleEditorRef"
              :defaultConfig="toolbarConfig"
            />
            <Editor
              style="height: 200px; overflow-y: hidden"
              v-model="newQuestion.outputContent"
              :defaultConfig="editorConfig"
              @onCreated="handleOutputExampleCreated"
            />
          </div>
        </el-form-item>
        <!-- 测试输入内容 -->
        <el-form-item label="测试输入内容" required>
          <el-button @click="addTestInput" type="primary" size="small"
            >添加测试输入</el-button
          >
          <div
            v-for="(testInput, index) in newQuestion.testInput"
            :key="'testInput-' + index"
            style="margin-top: 10px"
          >
            <el-input
              v-model="newQuestion.testInput[index]"
              placeholder="请输入测试输入内容"
            ></el-input>
            <el-button
              @click="removeTestInput(index)"
              type="danger"
              size="mini"
              style="margin-top: 5px"
              >删除</el-button
            >
          </div>
        </el-form-item>

        <!-- 测试输出内容 -->
        <el-form-item label="测试输出内容" required>
          <el-button @click="addTestOutput" type="primary" size="small"
            >添加测试输出</el-button
          >
          <div
            v-for="(testOutput, index) in newQuestion.testOutput"
            :key="'testOutput-' + index"
            style="margin-top: 10px"
          >
            <el-input
              v-model="newQuestion.testOutput[index]"
              placeholder="请输入测试输出内容"
            ></el-input>
            <el-button
              @click="removeTestOutput(index)"
              type="danger"
              size="mini"
              style="margin-top: 5px"
              >删除</el-button
            >
          </div>
        </el-form-item>

        <!-- 新增的字段 -->
        <el-form-item label="时间限制" required>
          <el-input type="number" v-model="newQuestion.timeLimit"></el-input>
        </el-form-item>
        <el-form-item label="内存限制" required>
          <el-input type="number" v-model="newQuestion.memoryLimit"></el-input>
        </el-form-item>
      </el-form>
      <el-form-item label="是否关闭">
        <el-switch v-model="newQuestion.isOpen" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAddQuestion">取 消</el-button>
        <el-button type="primary" @click="saveQuestion">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import request from "@/utils/request";
export default {
  components: {
    Editor,
    Toolbar,
  },
  data() {
    return {
      inputDescEditorRef: null,
      outputDescEditorRef: null,
      inputExampleEditorRef: null,
      outputExampleEditorRef: null,
      questions: [],
      dialogVisible: false,
      newQuestion: {
        title: "",
        content: "",
        tags: "",
        inputContent: "", // 输入样例（单个字符串）
        outputContent: "", // 输出样例（单个字符串）
        inputDescription: "", // 输入样例（单个字符串）
        outputDescription: "", // 输出样例（单个字符串）
        testInput: [], // 测试输入内容（后端用）
        testOutput: [], // 测试输出内容（后端用）
        timeLimit: null,
        memoryLimit: null,
        isOpen: 0,
        id: null, // 用于存储当前编辑题目的ID
      },
      editorRef: null, // 编辑器实例
      toolbarConfig: {}, // 工具栏配置
      editorConfig: { placeholder: "请输入内容..." }, // 编辑器配置
      toolbarConfig1: {}, // 工具栏配置
      editorConfig1: { placeholder: "请输入内容..." }, // 编辑器配置
    };
  },
  created() {
    this.fetchQuestions();
  },
  methods: {
    async fetchQuestions() {
      try {
        const res = await request.get("/problem/selectAllAdmin");
        this.questions = res.data;
      } catch (error) {
        console.error("获取题目数据失败:");
      }
    },

    editQuestion(question) {
      this.newQuestion = { ...question };
      if (question.judgeConfig) {
        const config = JSON.parse(question.judgeConfig);
        this.newQuestion.timeLimit = config.timeLimit;
        this.newQuestion.memoryLimit = config.memoryLimit;
      }
      if (question.judgeCase) {
        const caseData = JSON.parse(question.judgeCase);
        this.newQuestion.testInput = caseData.inputList || [];
        this.newQuestion.testOutput = caseData.outputList || [];
      }
      this.newQuestion.isOpen = question.isOpen || 0; // 如果没有值，默认设置为 0
      this.dialogVisible = true;
    },
    beforeUnmount() {
      if (this.editorRef) this.editorRef.destroy();
      if (this.inputDescEditorRef) this.inputDescEditorRef.destroy();
      if (this.outputDescEditorRef) this.outputDescEditorRef.destroy();
      if (this.inputExampleEditorRef) this.inputExampleEditorRef.destroy();
      if (this.outputExampleEditorRef) this.outputExampleEditorRef.destroy();
    },
    async saveQuestion() {
      const judgeConfig = {
        timeLimit: this.newQuestion.timeLimit,
        memoryLimit: this.newQuestion.memoryLimit,
      };

      // 格式化 judgeCase 中的测试输入和输出为列表格式
      const judgeCase = {
        inputList: this.newQuestion.testInput,
        outputList: this.newQuestion.testOutput,
      };

      const questionData = {
        title: this.newQuestion.title,
        content: this.newQuestion.content,
        tags: this.newQuestion.tags,
        inputContent: this.newQuestion.inputContent, // 保持为单个字符串
        outputContent: this.newQuestion.outputContent, // 保持为单个字符串
        inputDescription: this.newQuestion.inputDescription, // 保持为单个字符串
        outputDescription: this.newQuestion.outputDescription, // 保持为单个字符串
        judgeConfig: JSON.stringify(judgeConfig),
        judgeCase: JSON.stringify(judgeCase),
        isOpen: this.newQuestion.isOpen,
      };

      if (this.newQuestion.id) {
        try {
          const res = await request.put(
            `/problem/update/${this.newQuestion.id}`,
            questionData
          );
          if (res.code === "200") {
            this.dialogVisible = false;
            this.fetchQuestions();
            this.resetNewQuestion();
          } else {
            window.alert(res.msg);
          }
        } catch (error) {
          console.error("请求失败:");
        }
      } else {
        try {
          const res = await request.post("/problem/add", questionData);
          if (res.code === "200") {
            this.dialogVisible = false;
            this.fetchQuestions();
            this.resetNewQuestion();
          } else {
            window.alert(res.msg);
          }
        } catch (error) {
          console.error("请求失败:");
        }
      }
    },

    async deleteQuestion(questionId) {
      try {
        // 弹出确认框
        const confirmDelete = await this.$confirm(
          "确认删除这个题目吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        if (confirmDelete === "confirm") {
          // 用户确认删除，执行删除操作
          const res = await request.delete(`/problem/questions/${questionId}`);
          if (res.code === "200") {
            this.fetchQuestions(); // 刷新题目列表
          } else {
            console.error("删除题目失败");
          }
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("请求失败:");
        }
      }
    },
    cancelAddQuestion() {
      this.dialogVisible = false;
      this.resetNewQuestion();
    },

    resetNewQuestion() {
      this.newQuestion = {
        title: "",
        content: "",
        tags: "",
        inputContent: "", // 输入样例（单个字符串）
        outputContent: "", // 输出样例（单个字符串）
        inputDescription: "",
        outputDescription: "",
        testInput: [], // 测试输入内容（后端用）
        testOutput: [], // 测试输出内容（后端用）
        timeLimit: null,
        memoryLimit: null,
        id: null, // 用于存储当前编辑题目的ID
      };
    },

    handleCreated(editor) {
      // 确保编辑器实例只在创建时绑定一次
      if (!this.editorRef) {
        this.editorRef = editor;
      }
    },
    handleInputDescCreated(editor) {
      if (!this.inputDescEditorRef) {
        this.inputDescEditorRef = editor;
      }
    },
    handleOutputDescCreated(editor) {
      if (!this.outputDescEditorRef) {
        this.outputDescEditorRef = editor;
      }
    },
    handleInputExampleCreated(editor) {
      if (!this.inputExampleEditorRef) {
        this.inputExampleEditorRef = editor;
      }
    },
    handleOutputExampleCreated(editor) {
      if (!this.outputExampleEditorRef) {
        this.outputExampleEditorRef = editor;
      }
    },
    addTestInput() {
      this.newQuestion.testInput.push("");
    },

    removeTestInput(index) {
      this.newQuestion.testInput.splice(index, 1);
    },

    addTestOutput() {
      this.newQuestion.testOutput.push("");
    },

    removeTestOutput(index) {
      this.newQuestion.testOutput.splice(index, 1);
    },
    handleClose(done) {
      done();
      this.resetNewQuestion();
    },
  },
};
</script>

<style scoped>
.create-post-layout {
  background-color: #f5f5f5;
  padding: 30px 0;
}

.create-post-container {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 1000px;
  margin: 0 auto;
}

h2 {
  text-align: center;
  margin-bottom: 30px;
}

.create-post-form .ant-btn {
  width: 600px;
}
</style>
